#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   ninja.py
@Time    :   2023/11/09 14:50:33
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from typing import Any, List

from django.db.models import QuerySet
from django.http import HttpRequest, HttpResponse
from ninja import Field,NinjaAPI,Schema
from ninja.pagination import PaginationBase
from ninja.types import DictStrAny


class MyPagination(PaginationBase):
    class Input(Schema):
        pageSize: int = Field(10, gt=0)  # 分页大小，默认为10，必须大于0
        page: int = Field(1, gt=-1)  # 当前页，默认为1，必须大于-1

    class Output(Schema):
        items: List[Any]  # 当前页的数据列表
        total: int  # 总数

    def paginate_queryset(
        self,
        queryset: QuerySet,  # 查询集对象
        pagination: Input,  # 分页对象
        **params: DictStrAny,  # 其他参数
    ) -> Any:  # 返回任意类型
        offset = pagination.pageSize * (pagination.page - 1)  # 计算偏移量
        limit: int = pagination.pageSize  # 分页大小
        return {
            "page": offset,  # 当前页
            "limit": limit,  # 分页大小
            "items": queryset[offset : offset + limit],  # 当前页的数据
            "total": self._items_count(queryset),  # 总数
        }


class BaseNinjaAPI(NinjaAPI):
    def create_response(
        self,
        request: HttpRequest,
        data: Any,
        *,
        status: int = 200,
        code: int = 200,
        msg: str = "success",
        temporal_response: HttpResponse = None,
    ) -> HttpResponse:
        std_data = {"code": code, "result": data, "message": msg, "success": True}
        content = self.renderer.render(request, std_data, response_status=status)
        content_type = "{}; charset={}".format(
            self.renderer.media_type, self.renderer.charset
        )
        return HttpResponse(content, status=status, content_type=content_type)
